const { getAll, add, update, remove } = require('../../utils/dbTools');
const { arrToTree } = require('../../utils/util');
// 数据表名称
const tableName = 'region';
/**
 * 查询地区列表
 */
const regionList = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { page, size, istree } = req.query;
    const params = {};
    if (page && size) {
        params.page = page;
        params.size = size;
    }
    const result = await getAll(tableName, params);
    output.data = istree == 1 ? arrToTree(result) : result;
    res.send(output);
}

/**
 * 新增地区
 * 
 */
const regionAdd = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { name, type, pid } = req.body;
    if (!name || !type || !pid) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }

    // 检测地区名称是否可用
    const valid = await isValidator(tableName, 'name', name);
    if (!valid) {
        output.code = 500;
        output.msg = '数据已存在,不能重复添加';
        return res.send(output);
    }

    const result = await add({ name, pid, type }, tableName);
    if (!result) {
        output.code = 500;
        output.msg = '操作失败';
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

/**
 * 更新地区信息
*/
const regionUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id, name, type, pid } = req.body;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }
    const data = {};
    if (name) data.name = name;
    if (type) data.type = type;
    if (pid) data.pid = pid;

    const result = await update(id, data, tableName);
    if (!result) {
        output.code = 500;
        output.msg = '操作失败';
        return res.send(output);
    }
    res.send(output);
}
/**
 * 删除地区
*/

const regionRemove = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id } = req.query;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }
    const result = await remove(id, tableName);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    res.send(output);
}

module.exports = {
    regionList,
    regionAdd,
    regionUpdate,
    regionRemove
}